<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/4/30
 * Time: 22:47
 */

namespace app\admin\controller;


use app\common\model\BusInquiry;
use app\common\model\BusInquiryDetail;
use app\common\model\BusInquiryDetailSupplier;
use app\common\model\BusInquirySuppliers;
use app\common\model\SalesCompany;
use app\common\model\SuppliersCompany;
use app\common\model\SysConfig;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;

class Quotation extends Admin
{
    protected $quiltyChoose = [
        'service'=>'qulity_service_price',
        'org'=>'qulity_org_price',
        'matching'=>'qulity_matching_price',
        'complete'=>'qulity_complete_price',
        'suitable'=>'qulity_suitable_price'
    ];

    /**
     * 获取公司列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getList(){
        $page = input('page', 1);
        $limit = input('limit', 20);
        $due_date = input('due_date','');
        $param = $this->getParam();
        if($due_date){
            $date_arr = explode(' - ',$due_date);
            if(!empty($date_arr)){
                $param['quote_datetime'] = ['between', [trim($date_arr[0]), date('Y-m-d', strtotime ("+1 day", strtotime(trim($date_arr[1]))))]];
            }
        }
        $param['sale_price_state'] = ['>',0];
        $model = new BusInquiry();
        $count = $model->where($param)->count();
        if($page > ceil($count/$limit)){
            $page = ceil($count/$limit);
        }
        $lst = $model->where($param)->order('quote_datetime desc,id desc')->page($page,$limit)->select();
        return json_tab_msg($count,$page,$lst);
    }

    /**
     * 询价详情表
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getQutationInfo()
    {
        $id = input('id');
        $model = new BusInquiry();
        $supplierModel = new SuppliersCompany();
        $info = $model->where(['id'=>$id])->find();
        $info['suppliers'] = $supplierModel->where(['id'=>['in',$info['bus_to_company_ids']]])->field('id,suppliers_company_name')->select();

        $configModel = new SysConfig();
        $tax =  $configModel->where(['name'=>'tax'])->find();
        $info['sys_tax_rate'] = $tax['val']['content'];
        json_return_code($info);
    }

    public function getSupplierPrice()
    {
        $id = input('id');
        $supplier_id =input('supplier_id');
        $type =input('type',1);
        $org_profit_rate =input('org_profit_rate',0)?:0;
        $matching_profit_rate =input('matching_profit_rate',0)?:0;
        $complete_profit_rate =input('complete_profit_rate',0)?:0;
        $suitable_profit_rate =input('suitable_profit_rate',0)?:0;
        $param = ['bus_inquiry_id'=>$id,'add_company_id'=>$supplier_id];
        $supplierDetailModel = new BusInquiryDetailSupplier();
        $sum_num = $supplierDetailModel->where($param)->sum('num');
        $detail_info= $supplierDetailModel->with(['company','detail'])->where($param)->order('order_no asc,id asc')->select();
        $model = new BusInquiry();
        $sale_price_state = $model->where(['id'=>$id])->value('sale_price_state');

        // 合计
        $qulity_service_price = 0;
        $qulity_org_price = 0;
        $qulity_matching_price = 0;
        $qulity_complete_price = 0;
        $qulity_suitable_price = 0;

        $quote_service_price = 0;
        $quote_org_price = 0;
        $quote_matching_price = 0;
        $quote_complete_price = 0;
        $quote_suitable_price = 0;

        // 配件总价
        $supplier_sum = 0;
        $sure_sum = 0;
        foreach ($detail_info as $item){
            $item['qulity_service_price'] =$item['state']>2?$item['qulity_service_price']:0;
            $item['qulity_org_price'] = $item['state']>2?$item['qulity_org_price']:0;
            $item['qulity_matching_price'] = $item['state']>2?$item['qulity_matching_price']:0;
            $item['qulity_complete_price'] = $item['state']>2?$item['qulity_complete_price']:0;
            $item['qulity_suitable_price'] = $item['state']>2?$item['qulity_suitable_price']:0;

            $item['total_service_price'] = $item['qulity_service_price'];
            $item['total_org_price']     = ($item['detail']['qulity_org_price']>0 || $item['detail']['qulity_org_price']===0)?$item['detail']['qulity_org_price']:round(floatval($item['qulity_org_price'])*(100+$org_profit_rate)/100);
            $item['total_matching_price'] = ($item['detail']['qulity_matching_price']>0 || $item['detail']['qulity_matching_price']===0)?$item['detail']['qulity_matching_price']:round(floatval($item['qulity_matching_price'])*(100+$matching_profit_rate)/100);
            $item['total_complete_price'] = ($item['detail']['qulity_complete_price']>0 || $item['detail']['qulity_complete_price']===0)?$item['detail']['qulity_complete_price']:round(floatval($item['qulity_complete_price'])*(100+$complete_profit_rate)/100);
            $item['total_suitable_price'] = ($item['detail']['qulity_suitable_price']>0 || $item['detail']['qulity_suitable_price']===0)?$item['detail']['qulity_suitable_price']:round(floatval($item['qulity_suitable_price'])*(100+$suitable_profit_rate)/100);
            $qulity_service_price += $item['qulity_service_price'];
            $qulity_org_price += $item['qulity_org_price'];
            $qulity_matching_price += $item['qulity_matching_price'];
            $qulity_complete_price += $item['qulity_complete_price'];
            $qulity_suitable_price += $item['qulity_suitable_price'];

            $quote_service_price += $item['total_service_price'];
            $quote_org_price += $item['total_org_price'];
            $quote_matching_price += $item['total_matching_price'];
            $quote_complete_price += $item['total_complete_price'];
            $quote_suitable_price += $item['total_suitable_price'];

            $make_sure_quilty = $item['make_sure_quilty']?:((!$item['make_sure_quilty'] && count($item['detail']['quote_quilty']) == 1)?$this->quiltyChoose[$item['detail']['quote_quilty'][0]]:'');
            $sale_use_quilty = $item['detail']['sale_use_quilty']?:((!$item['detail']['sale_use_quilty'] && count($item['detail']['quote_quilty']) == 1)?$this->quiltyChoose[$item['detail']['quote_quilty'][0]]:'');
            if($make_sure_quilty){
                $supplier_sum += $item[$make_sure_quilty];
            }
            if($sale_use_quilty){
                $sure_sum += $item['detail'][$sale_use_quilty];
            }
        }
        $addData = [
            [
                'bus_inquiry_id'=>$id,
                'add_company_id'=>$supplier_id,
                'id'=>-1,
                'eq_name'=>'合计',
                'num'=>$sum_num,
                'qulity_service_price'=>round($qulity_service_price),
                'qulity_org_price'=>round($qulity_org_price),
                'qulity_matching_price'=>round($qulity_matching_price),
                'qulity_complete_price'=>round($qulity_complete_price),
                'qulity_suitable_price'=>round($qulity_suitable_price),
                'total_service_price'=>round($quote_service_price),
                'total_org_price'=>round($quote_org_price),
                'total_matching_price'=>round($quote_matching_price),
                'total_complete_price'=>round($quote_complete_price),
                'total_suitable_price'=>round($quote_suitable_price),
            ],
        ];

        if($sale_price_state>1 || $type==2){
            $addData[] = [
                'id'=>-2,
                'eq_name'=>'配件总价',
                'bus_inquiry_id'=>$id,
                'add_company_id'=>$supplier_id,
                'num'=>$sum_num,
                'supplier_sum'=>round($supplier_sum),
                'sure_sum'=>round($sure_sum),
            ];
        }
        $info['detail_info'] = $detail_info;
        $info['all_info'] = $addData;
        json_return_code($info);
    }

    /**
     * 生成报价单
     * @return void
     * @throws PDOException
     */
    public function createQuotation()
    {
        $data = $this->trimParam();
        $detail_info = json_decode($data['detail_info'],true);
        $detail_data = [];
        $supplier_data = [];
        foreach ($detail_info as $item){
            $detail_data[] = [
                'id'=>$item['bus_inquiry_detail_id'],
                'quote_quilty'=>$item['quote_quilty'],
                'add_company_id'=>$data['add_company_id'],
                'state'=>$item['quote_quilty']?3:2,
                'qulity_service_price'=>$item['total_service_price'],
                'qulity_org_price'=>$item['total_org_price'],
                'qulity_matching_price'=>$item['total_matching_price'],
                'qulity_complete_price'=>$item['total_complete_price'],
                'qulity_suitable_price'=>$item['total_suitable_price'],
            ];
            $supplier_data[] = [
                'id'=>$item['id'],
                'quote_quilty'=>$item['quote_quilty'],
            ];
        }

        $inquiryModel = new BusInquiry();
        $detailModel = new BusInquiryDetail();
        $supplierDetailModel = new BusInquiryDetailSupplier();
        try {
            $detailModel->startTrans();
            //询价单详情修改
            $detailModel->saveAll($detail_data);
            //供应商详情修改
            $supplierDetailModel->saveAll($supplier_data);

            $from_quotation_selection_json['add_company_id'] = $data['add_company_id'];
            $supplierModel = new SuppliersCompany();
            $from_quotation_selection_json['add_company_name'] = $supplierModel->where(['id'=>$data['add_company_id']])->value('suppliers_company_name');
            $from_quotation_selection_json['org_profit_rate'] = $data['org_profit_rate']??'';
            $from_quotation_selection_json['matching_profit_rate'] = $data['matching_profit_rate']??'';
            $from_quotation_selection_json['complete_profit_rate'] = $data['complete_profit_rate']??'';
            $from_quotation_selection_json['suitable_profit_rate'] = $data['suitable_profit_rate']??'';
            $from_quotation_selection_json['eq_info'] = $detail_data;
            $inquiry_data = [
                'tax_rate'=>$data['tax_rate'],
                'sale_price_state'=>1,
                'quote_company_name'=>$from_quotation_selection_json['add_company_name'],
                'quote_company_id'=>$data['add_company_id'],
                'from_quotation_selection_json'=>json_encode($from_quotation_selection_json), //供应商
                'to_quotation_selection_json'=>json_encode($supplier_data), //销售商
            ];
            $inquiryModel->isUpdate(true)->save($inquiry_data,['id'=>$data['id']]);
            $detailModel->commit();
            addLog('生成报价单');
            //生成报价单文件
            json_return_code();
        }catch (Exception $e){
            $detailModel->rollback();
            json_return_code('','操作失败'.$e->getMessage(),201);
        }

    }

    /**
     * 生成报价文件
     * @return void
     */
    public function createQuotationFile()
    {
        $data = $this->trimParam();
        $inquiryModel = new BusInquiry();
        $inquiryModel->createQuotationFile($data);
    }

    /**
     * 确认中标完善报价信息
     * @return void
     */
    public function editQuotation()
    {
        $data = $this->trimParam();
        $id = $data['id'];
        $add_company_id = $data['add_company_id'];
        $detail_infos = json_decode($data['detail_info'],true);
        unset($data['id']);
        unset($data['add_company_id']);
        unset($data['detail_info']);

        $inquiryModel = new BusInquiry();
        $supplierCompanyModel = new SuppliersCompany();

        $detail_data = [];
        $supplier_detail_date = [];
        $detail_totall_price = 0;
        $supplier_totall_price = 0;

        $supplier_company = $supplierCompanyModel->field('tax_rate,suppliers_company_name')->where(['id'=>$add_company_id])->find();

        foreach ($detail_infos as $item){
            if(!$item['detail']['sale_use_quilty'] && count($item['detail']['quote_quilty']) == 1){
                $item['detail']['sale_use_quilty'] = $this->quiltyChoose[$item['detail']['quote_quilty'][0]];
            }
            if(!$item['make_sure_quilty'] && count($item['detail']['quote_quilty']) == 1){
                $item['make_sure_quilty'] = $this->quiltyChoose[$item['detail']['quote_quilty'][0]];
            }

            $supplier_quilty = $item['make_sure_quilty'];
            $detail_quilty = $item['detail']['sale_use_quilty'];
            if($supplier_quilty){
                $supplier_info = [
                    'id'=>$item['id'],
                    'state'=>5,
                    'make_sure_quilty'=>$supplier_quilty,
                    'totall_price'=>round($item[$supplier_quilty]*$item['num']),

                ];
                $supplier_detail_date[] = $supplier_info;
                $supplier_totall_price += $supplier_info['totall_price'];
            }

            if($detail_quilty){
                $detail_info = [
                    'id'=>$item['detail']['id'],
                    'state'=>5,
                    'sale_use_quilty'=>$detail_quilty,
                    'totall_price'=>round($item['detail'][$detail_quilty]*$item['num']),
                    'oe_no'=>$item['oe_no'],
                ];
                $detail_data[] = $detail_info;
                $detail_totall_price += $detail_info['totall_price'];
            }
        }

        $data['sure_user_id'] = $data['opt_user_id'];
        $data['sure_user_name'] = $data['opt_user_name'];
        $data['sure_datetime'] = date('Y-m-d H:i:s');
        $supplier_data = $data;

        $data['totall_price'] = $detail_totall_price;
        $data['sale_price_state'] = 3;
        $data['sure_company_name'] = $supplier_company['suppliers_company_name'];
        $data['sure_company_id'] = $add_company_id;

        $supplier_data['totall_price'] = $supplier_totall_price;
        $supplier_data['tax_rate'] = $supplier_company['tax_rate'];
        $supplier_data['state'] = 6;
        unset($supplier_data['freight']);

        try {
            $inquiryModel->startTrans();

            $detailModel = new BusInquiryDetail();
            $supplierModel = new BusInquirySuppliers();
            $supplierDetailModel = new BusInquiryDetailSupplier();

            if(!$data['sales_no']){
                $sales_no = generateUniqueOrderno();
                $data['sales_no']= $sales_no;
                $data['sales_datetime']= date('Y-m-d H:i:s');
                $data['sales_no']= $sales_no;
                $data['sales_datetime']= date('Y-m-d H:i:s');
            }
            $detailModel->saveAll($detail_data);
            $supplierDetailModel->saveAll($supplier_detail_date);

            $inquiryModel->isUpdate(true)->save($data,['id'=>$id]);
            $supplierModel->isUpdate(true)->save($supplier_data,['bus_inquiry_id'=>$id,'bus_to_company_id'=>$add_company_id]);
            $supplierModel->isUpdate(true)->save([
                'state'=>7,
                'sure_datetime'=>date('Y-m-d H:i:s'),
            ],['bus_inquiry_id'=>$id,'bus_to_company_id'=>['<>',$add_company_id],'state'=>2]); //未中标
            $inquiryModel->commit();
            json_return_code();
        }catch (\Exception $e){
            $inquiryModel->rollback();
            json_return_code('','操作失败'.$e->getMessage(),201);
        }
    }

    public function createSalesPurchaseFile()
    {
        $data = $this->trimParam();
        $inquiryModel = new BusInquiry();
        $inquiryModel->createSalesPurchaseFile($data);
    }

    /**
     * 报价价格修改
     * @return void
     */
    public function editPrice()
    {
        $data = $this->trimParam();
        $up_data[$data['tag_name']] = $data['price'];
        $detailModel = new BusInquiryDetail();
        $detailSupplierModel = new BusInquiryDetailSupplier();
        try {
            $detailModel->startTrans();
            if($data['tag_type'] === 'supplier'){
                if($data['tag_name'] == 'qulity_service_price'){
                    $detailModel->isUpdate(true)->save($up_data,['id'=>$data['detail_id']]);
                }
                $up_data['state'] = 3;
                $detailSupplierModel->isUpdate(true)->save($up_data,['id'=>$data['id']]);
            }else{
                $detailModel->isUpdate(true)->save($up_data,['id'=>$data['id']]);
                if($data['tag_name'] == 'qulity_service_price'){
                    $up_data['state'] = 3;
                    $detailSupplierModel->isUpdate(true)->save($up_data,['id'=>$data['detail_id']]);
                }
            }
            $detailModel->commit();
            addLog('修改询价单价格');
            json_return_code();
        }catch (Exception $e){
            $detailModel->rollback();
            json_return_code('','操作失败',201);
        }
    }



    /**
     * 修改报价所选品质
     * @return void
     * @throws PDOException
     */
    public function editQuoteQuilty()
    {
        $data = input();
        $detailModel = new BusInquiryDetail();
        $supplierDetailModel = new BusInquiryDetailSupplier();
        try {
            $detailModel->startTrans();
            //询价单详情修改
            $detailModel->isUpdate(true)->save(['quote_quilty'=>$data['quote_quilty']],['id'=>$data['bus_inquiry_detail_id']]);
            //供应商详情修改
            $supplierDetailModel->isUpdate(true)->save(['quote_quilty'=>$data['quote_quilty']],['id'=>$data['id']]);

            $detailModel->commit();
            addLog('修改报价品质');
            //生成报价单文件
            json_return_code();
        }catch (Exception $e){
            $detailModel->rollback();
            json_return_code('','操作失败'.$e->getMessage(),201);
        }
    }

    public function editSureQuilty()
    {
        $data = input();
        $detailModel = new BusInquiryDetail();
        $supplierDetailModel = new BusInquiryDetailSupplier();
        try {
            $detailModel->startTrans();
            //询价单详情修改
            if($data['sale_use_quilty']){
                $detailModel->isUpdate(true)->save(['sale_use_quilty'=>$data['sale_use_quilty']],['id'=>$data['bus_inquiry_detail_id']]);
            }
            //供应商详情修改
            if($data['make_sure_quilty']) {
                $supplierDetailModel->isUpdate(true)->save(['make_sure_quilty' => $data['make_sure_quilty']],['id' => $data['id']]);
            }
            $detailModel->commit();
            addLog('修改供货采购品质');
            //生成报价单文件
            json_return_code();
        }catch (Exception $e){
            $detailModel->rollback();
            json_return_code('','操作失败'.$e->getMessage(),201);
        }
    }
}